package com.esiran.payadmin.controller;

import com.esiran.payadmin.entity.FormField;
import com.esiran.payadmin.entity.FormInputField;
import com.esiran.payadmin.entity.FormModel;
import com.esiran.payadmin.exception.APIRespException;
import com.esiran.payadmin.service.UserService;
import com.esiran.payadmin.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public String index() {
        return "user/index";
    }
    @GetMapping("test")
    public String test(ModelMap modelMap) {
        FormModel formModel = new FormModel();
        List<FormField> fields = new ArrayList<>();
        FormInputField inputField = new FormInputField.Builder()
                .setPlaceholder("请输入分类名称")
                .setAutocomplete(false)
                .addRule("required","true","请输入分类名称")
                .addRule("minlength","6","不能少于6个字符")
                .create("name","分类名称");
        fields.add(inputField);
        formModel.setFormFields(fields);
        formModel.setSubmitName("确定");
        formModel.setCanCancel(true);
        modelMap.addAttribute("formModel",formModel);
        return "user/test";
    }
    @GetMapping("login")
    public String login(){
        return "user/login";
    }
    @PostMapping("login")
    public String doLogin(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse httpServletResponse){
        try {
            String token = userService.login(username,password);
            Cookie tokenCookie = new Cookie("token_v1",token);
            CookieUtil.addCookie(httpServletResponse,tokenCookie);
            return "redirect:/user";
        } catch (APIRespException e) {
            return "redirect:/user/login?err=1";
        }
    }
}
